package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    RedisTemplate<String, Object> redisTemplate;

    public DictServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("Excel导入成功");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Dict::getId, Dict::getParentId, Dict::getName, Dict::getValue, Dict::getDictCode);
        List<Dict> dictList = baseMapper.selectList(lambdaQueryWrapper);
        return dictList.stream().map(this::convert).collect(Collectors.toList());
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        // 查redis
        try {
            log.info("从redis中获取数据列表");
            List<Dict> dictListCache = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dictListCache != null) {
                log.info("从redis中获取数据列表成功");
                return dictListCache;
            }
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }
        //没缓存查数据库
        log.info("从数据库中获取数据列表");
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId, parentId);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        ArrayList<Long> ids = new ArrayList<>();
        dictList.forEach(dict -> ids.add(dict.getId()));
        QueryWrapper<Dict> childrenQueryWrapper = new QueryWrapper<>();
        childrenQueryWrapper.select("DISTINCT parent_id").in("parent_id", ids);
        List<Object> existIds = baseMapper.selectObjs(childrenQueryWrapper);
        dictList.forEach(dict -> dict.setHasChildren(existIds.contains(dict.getId())));

        //redis存值
        try {
            log.info("将数据存入redis");
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
            log.info("数据已存入redis");
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 查redis
        try {
            log.info("从redis中获取数据列表");
            List<Dict> dictListCache = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + dictCode);
            if (dictListCache != null) {
                log.info("从redis中获取数据列表成功");
                return dictListCache;
            }
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }

        //没缓存查数据库
        log.info("从数据库中获取数据列表");
        List<Dict> dictList = baseMapper.findByDictCode(dictCode);

        //redis存值
        try {
            log.info("将数据存入redis");
            redisTemplate.opsForValue().set("srb:core:dictList:" + dictCode, dictList, 5, TimeUnit.MINUTES);
            log.info("数据已存入redis");
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }

        return dictList;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        // 查redis
        try {
            log.info("从redis中获取数据列表");
            List<Dict> dictListCache = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + dictCode);
            if (dictListCache != null) {
                log.info("从redis中获取数据列表成功");
                for (Dict dict : dictListCache) {
                    if (value.equals(dict.getValue())) {
                        return dict.getName();
                    }
                }
                return "";
            }
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }

        //没缓存查数据库
        log.info("从数据库中获取数据名");

        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode, dictCode);
        Dict parentDict = baseMapper.selectOne(queryWrapper);

        if (parentDict == null) {
            return "";
        }

        queryWrapper.clear();
        queryWrapper.select(Dict::getName)
                .eq(Dict::getParentId, parentDict.getId())
                .eq(Dict::getValue, value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if (dict == null) {
            return "";
        }
        return dict.getName();
    }

    @Deprecated
    private boolean hasChildren(Long parentId) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, parentId);
        Long count = baseMapper.selectCount(lambdaQueryWrapper);
        return count > 0;
    }

    private ExcelDictDTO convert(Dict dict)  {
        ExcelDictDTO excelDictDTO = new ExcelDictDTO();
        BeanUtils.copyProperties(dict, excelDictDTO);
        return excelDictDTO;
    }
}
